package org.light.reflecttable.facade;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.light.reflecttable.domain.Database;
import org.light.reflecttable.service.DatabaseService;
import org.light.reflecttable.serviceimpl.DatabaseServiceImpl;
import org.light.reflecttable.serviceimpl.TableServiceImpl;

import net.sf.json.JSONArray;

public class ListAllDatabasesFacade extends HttpServlet{

	protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		response.setContentType("application/json;charset=UTF-8");
		Map<String,Object> result = new TreeMap<String,Object>();
		PrintWriter out = response.getWriter();
		String dbType = TableServiceImpl.dbType;
		try {			
			DatabaseService service = new DatabaseServiceImpl();
			List<Database> list = new ArrayList<>();
			if ("MariaDB".equalsIgnoreCase(dbType)||"MySQL".equalsIgnoreCase(dbType)) {
				System.out.println(dbType);
				list = service.listAllDatabases();
			} else if ("PostgreSQL".equalsIgnoreCase(dbType)||"pgsql".equalsIgnoreCase(dbType)) {
				System.out.println(dbType);
				list = service.listAllPgDatabases();
			} 
			result.put("success",true);
			result.put("rows",list);
			out.print(JSONArray.fromObject(list).toString());
		} catch (Exception e){
			e.printStackTrace();
			out.print(JSONArray.fromObject(new ArrayList<>()).toString());
		} finally {
			out.close();
		}
	}

	public String getServletInfo(){
		return "Powered by Mind Rules.";
	}

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		processRequest(request, response);
	}

}
